package com.tech.distribute_id.zk;

import com.tech.distribute_id.AbstractDistributeIdStrategy;
import com.tech.distribute_id.StrategyTypeEnum;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.ACLBackgroundPathAndBytesable;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author litianlin
 * @date 2023/11/23 18:21
 * @description: zk方案，curator框架，顺序节点、节点版本号
 */
@Component
public class ZkDistributeIdStrategy extends AbstractDistributeIdStrategy {

    @Resource(name = "curatorClient")
    private CuratorFramework client;

    @Override
    public StrategyTypeEnum getStrategyType() {
        return StrategyTypeEnum.ZK;
    }

    @Override
    public String getDistributeId() throws Exception {
        ACLBackgroundPathAndBytesable<String> creator = client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL);
        Stat stat = client.checkExists().forPath("/seq");
        if(stat==null){
            ACLBackgroundPathAndBytesable<String> creator2 = client.create().withMode(CreateMode.PERSISTENT);
            creator2.forPath("/seq");
        }
        creator.forPath("/seq/id");
        List<String> forPath = client.getChildren().forPath("/seq");
        return forPath.get(forPath.size()-1);
    }
}
